package com.syq.controller;

import com.syq.annotation.RequiresPermissionsDesc;
import com.syq.pojo.DtsStorage;
import com.syq.service.DtsStorageService;
import com.syq.util.ResponseUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @ClassName: StorageController
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/7/26 9:12
 */

@RestController
@RequestMapping("admin/storage")
@CrossOrigin
public class StorageController {
    @Autowired
    private DtsStorageService dtsStorageService;


    @PostMapping("/create")
    public Object create(MultipartFile file) throws Exception{
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        DtsStorage dtsStorage=dtsStorageService.uploadFile(file.getBytes(),ext,(int)file.getSize(),file.getOriginalFilename());
        if (null==dtsStorage){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(dtsStorage);
    }

    @RequiresPermissionsDesc(menu = {"系统管理","对象存储"},button = "查询")
    @RequiresPermissions(value = "admin:storage:list")
    @GetMapping("/list")
    public Object userList(@RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit, String key,String name,
                           @RequestParam(defaultValue = "add_time") String sort,
                           @RequestParam(defaultValue = "desc") String order){
    return dtsStorageService.findAll(page,limit,key,name,sort,order);
    }

    @RequiresPermissionsDesc(menu = {"系统管理","对象存储"},button = "编辑")
    @RequiresPermissions(value = "admin:storage:update")
    @PostMapping("/update")
    public Object update(@RequestBody DtsStorage dtsStorage,MultipartFile file) throws Exception {
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        DtsStorage storage=dtsStorageService.update(dtsStorage,file.getBytes(),ext,(int)file.getSize(),file.getOriginalFilename());
        return ResponseUtil.ok(storage);
    }

    @RequiresPermissionsDesc(menu = {"系统管理","对象存储"},button = "删除")
    @RequiresPermissions(value = "admin:storage:delete")
    @GetMapping("/delete")
    public Object deleted(@RequestBody DtsStorage dtsStorage){
        return dtsStorageService.delete(dtsStorage);
    }
}
